package api

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/charmbracelet/bubbles/key"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/huh"
)

const (
	InputHeight = 5
	TextHeight  = 20
)

func runCommand(message string) error {
	message = strings.ReplaceAll(message, "apt-get", "apt-get -y ")
	cmd := exec.Command("bash", "-c", message)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func runCommandWithValue(message string) (string, error) {
	cmd := exec.Command("bash", "-c", message)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("command execution error: %v, Output: %s", err, string(output))
	}
	return string(output), nil
}

func chatTextBox(input *string) *huh.Form {
	return huh.NewForm(
		huh.NewGroup(
			huh.NewText().
				ShowLineNumbers(true).
				Description("").
				Value(input).
				WithHeight(TextHeight),
		),
	).WithShowHelp(true).
		WithKeyMap(&huh.KeyMap{
			Quit: key.NewBinding(
				key.WithKeys("ctrl+c"),
			),
			Text: huh.TextKeyMap{
				Editor: key.NewBinding(
					key.WithKeys(""),
					key.WithHelp("<Ctrl+c>", "取消 ×  "),
				),
				Submit: key.NewBinding(
					key.WithKeys("enter"),
					key.WithHelp("  <Enter>", "运行 √"),
				),
				Next: key.NewBinding(
					key.WithKeys("pgdown", "down"),
					key.WithHelp("<↓/pgdn>", "下一行"),
				),
				Prev: key.NewBinding(
					key.WithKeys("pgup", "up"),
					key.WithHelp("<↑/pgup>", "上一行"),
				),
			},
		}).WithProgramOptions(tea.WithAltScreen()).
		WithHeight(TextHeight)
}

func inputBox(input *string) *huh.Form {
	return huh.NewForm(
		huh.NewGroup(
			huh.NewInput().
				Description("").
				Value(input),
		),
	).WithShowHelp(true).
		WithKeyMap(&huh.KeyMap{
			Quit: key.NewBinding(
				key.WithKeys("ctrl+c"),
			),
			Input: huh.InputKeyMap{
				Submit: key.NewBinding(
					key.WithKeys("enter"),
					key.WithHelp("[输入命令按下回车]", "    <Enter> √    <Ctrl+c> ×"),
				),
			},
		}).WithHeight(InputHeight)
}
